<template>
  <div justify="space-between">
    <h2>空间成员管理</h2>
  </div>
  <a-form layout="inline" :model="formData" @finish="handleSubmit">
    <a-form-item label="用户 id" name="userId">
      <a-input v-model:value="formData.userId" placeholder="请输入用户 id" allow-clear />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit">添加用户</a-button>
    </a-form-item>
    <!-- 添加用户选择和按钮 -->
    <a-form-item label="选择用户">
      <a-cascader
        v-model:value="selectedUserPath"
        :options="userOptions"
        placeholder="请选择用户"
        change-on-select
        style="width: 200px"
      />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" @click="addSelectedUser" :disabled="!selectedUserPath || selectedUserPath.length === 0">
        添加选中用户
      </a-button>
    </a-form-item>
  </a-form>
  <a-table :columns="columns" :data-source="dataList">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'userInfo'">
        <a-space>
          <a-avatar :src="record.user?.userAvatar" />
          {{ record.user?.userName }}
        </a-space>
      </template>
      <template v-if="column.dataIndex === 'spaceRole'">
        <a-select
          v-model:value="record.spaceRole"
          :options="SPACE_ROLE_OPTIONS"
          @change="(value) => editSpaceRole(value, record)"
        />
      </template>
      <template v-else-if="column.dataIndex === 'createTime'">
        {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space wrap>
          <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
        </a-space>
      </template>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
import { SmileOutlined } from '@ant-design/icons-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { type CascaderProps, message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_ENUM, SPACE_LEVEL_OPTIONS } from '../../constants/space'
import {
  addSpaceUserUsingPost,
  deleteSpaceUserUsingPost,
  editSpaceUserUsingPost,
  listSpaceUserUsingPost
} from '@/api/spaceUserController.ts'
import { SPACE_ROLE_OPTIONS } from '@/constants/space-permission.ts'
import { getAllUserVoInfoUsingGet } from '@/api/userController.ts'

// 表格列
const columns = [
  {
    title: '用户',
    dataIndex: 'userInfo'
  },
  {
    title: '角色',
    dataIndex: 'spaceRole'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    key: 'action'
  }
]

// 定义属性
interface Props {
  id: string
}

const props = defineProps<Props>()

// 数据
const dataList = ref([])
const selectedUserPath = ref<number[]>([]) // 存储选中的用户路径
const userOptions = ref<CascaderProps['options']>([]) // 用户选项

// 获取数据
const fetchData = async () => {
  const spaceId = props.id
  if (!spaceId) {
    return
  }
  const res = await listSpaceUserUsingPost({
    spaceId
  })
  if (res.data.data) {
    dataList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 获取所有用户信息
const fetchUsers = async () => {
  const res = await getAllUserVoInfoUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 将用户数据转换为级联选择器的格式
    userOptions.value = res.data.data.map((user: API.UserVO) => ({
      value: user.id,
      label: `${user.userName} (${user.userAccount})`,
      // 如果需要更复杂的层级结构，可以在这里添加children字段
    }))
  } else {
    message.error('获取用户信息失败，' + res.data.message)
  }
}

// 添加选中的用户到空间
const addSelectedUser = async () => {
  // 检查是否选择了用户
  if (!selectedUserPath.value || selectedUserPath.value.length === 0) {
    message.warning('请先选择用户')
    return
  }

  // 获取选中的用户ID（级联选择器的最后一个值就是用户ID）
  const userId = selectedUserPath.value[selectedUserPath.value.length - 1]

  if (!userId) {
    message.warning('请选择有效的用户')
    return
  }

  const spaceId = props.id
  if (!spaceId) {
    message.error('空间ID无效')
    return
  }

  try {
    // 调用添加用户接口
    const res = await addSpaceUserUsingPost({
      spaceId: spaceId,
      userId: userId,
    })

    if (res.data.code === 0) {
      message.success('用户添加成功')
      // 清空选择
      selectedUserPath.value = []
      // 刷新数据
      fetchData()
    } else {
      message.error('添加用户失败，' + res.data.message)
    }
  } catch (error: any) {
    message.error('添加用户失败：' + error.message)
  }
}

const editSpaceRole = async (value: string, record: any) => {
  const res = await editSpaceUserUsingPost({
    id: record.id,
    spaceRole: value
  })
  if (res.data.code === 0) {
    message.success('修改成功')
  } else {
    message.error('修改失败，' + res.data.message)
  }
}

const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  const res = await deleteSpaceUserUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

// 添加用户（通过用户ID输入框）
const formData = reactive<API.SpaceUserAddRequestDTO>({})

const handleSubmit = async () => {
  const spaceId = props.id
  if (!spaceId) {
    return
  }
  const res = await addSpaceUserUsingPost({
    spaceId,
    ...formData
  })
  if (res.data.code === 0) {
    message.success('添加成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('添加失败，' + res.data.message)
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
  fetchUsers()
})
</script>
